package com.bstek.service;

import com.bstek.dao.PermissionDao;
import com.bstek.dao.RoleUserDao;
import com.bstek.dao.UserDao;
import com.bstek.model.PermissionDto;
import com.bstek.model.RoleUserDto;
import com.bstek.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service(UserDetailService.BEAN_ID)
public class UserDetailService implements UserDetailsService {

    public static final String BEAN_ID = "cloud.userDetailService";

    @Autowired
    UserDao userDao;
    
    @Autowired
    RoleUserDao roleUserDao;

    @Autowired
    PermissionDao permissionDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            UserDto user =  userDao.getUserByUsername(username);
            Set<GrantedAuthority> userAuthotities = new HashSet<>();
            user.setAuthorities(getAuthorities(user));
            return user;
        } catch (Exception e) {
            System.out.println(e);
            throw new UsernameNotFoundException("Not Found");
        }
    }

    //查询user相关的权限信息
    private Set<GrantedAuthority> getAuthorities(UserDto user) {
        Set<GrantedAuthority> userAuthotities = new HashSet<>();
        List<RoleUserDto> rulist= roleUserDao.getRoleUserByUsername(user.getUserId());
        for (RoleUserDto roleUserDto: rulist) {
            List<PermissionDto> pers = permissionDao.searchPermissionByRoleId(roleUserDto.getRoleId());
            pers.forEach(permissionDto -> {
                userAuthotities.add(new SimpleGrantedAuthority(permissionDto.getAttribute()));
            });
        }
        return userAuthotities;
    }
}
